package org.nobody.mallb2c.mallseckill.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-28-13:14
 */
@Slf4j
@Component
@EnableAsync //←开启异步任务功能
@EnableScheduling
public class HelloSchedule {
  /** tip1
   * Spring中只能写6位的cron表达式,不允许【年】*/
  //Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid @Scheduled method 'hello': Cron expression must consist of 6 fields (found 7 in "*/5 * * * * ? 2020")
  //@Scheduled(cron = "*/5 * * * * ? 2020")

  /** tip2
   * Spring中周1就是1,周日就是7(不同于标准的cron)*/
  /*@Scheduled(cron = "* * * ? * 1")
  public void hello(){
    log.info("hello...");
  }*/

  /** tip3
   * 定时任务不应该阻塞,但spring中默认是阻塞的*/
  /*@Scheduled(cron = "* * * ? * 1")
  public void hello() throws InterruptedException {
    log.info("hello...");
    Thread.sleep(3000);
  }*/
  /** 解决方案①
   * 让业务以异步的方式运行*/
  /*@Scheduled(cron = "* * * ? * 1")
  public void hello() throws InterruptedException {
    log.info("hello...");
    CompletableFuture.runAsync(()->{
      xxxService.hello();
    });
  }*/
  /** 解决方案②
   * 让定时任务异步执行 @EnableAsync @Async
   * 定时任务 自动配置类参看 TaskSchedulingAutoConfiguration
   * 异步定时任务 自动配置类参看 TaskExecutionAutoConfiguration (也是靠的线程池实现的异步*/
  @Async
  @Scheduled(cron = "* * * ? * 1")
  public void hello() throws InterruptedException {
    log.info("hello...");
    Thread.sleep(3000);
  }
}
